use crate::models::products::{self, CreateParams};
use axum::{
    Json, Router,
    extract::State,
    routing::{get, post},
};
use loco_rs::prelude::*;

pub fn routes() -> Router<AppContext> {
    Router::new()
        .route("/products", post(create))
        .route("/products/:id", get(get_by_id))
        .route("/products/:id/delete", post(delete))
        .route("/products/by-slug/:slug", get(get_by_slug))
}

async fn create(
    State(state): State<AppContext>,
    Json(params): Json<CreateParams>,
) -> Result<Response> {
    let product = products::Model::create(&state.db, &params).await?;
    format::json(product)
}

async fn get_by_id(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Result<Response> {
    let product = products::Model::find_by_id(&state.db, &id).await?;
    format::json(product)
}

async fn delete(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Result<Response> {
    let product = products::Model::find_by_id(&state.db, &id).await?;
    let _result = products::Entity::delete_by_id(product.id)
        .exec(&state.db)
        .await?;
    format::json(())
}

async fn get_by_slug(
    State(state): State<AppContext>,
    axum::extract::Path(slug): axum::extract::Path<String>,
) -> Result<Response> {
    let product = products::Model::find_by_slug(&state.db, &slug).await?;
    format::json(product)
}
